classdef cga < eda
    properties
       popsize;
       varsize;
       margprob;
       fitfunc; 
       iters;
    end
    methods
        function obj = cga(popsize, varsize, fitfunc)
            obj.popsize = popsize;
            obj.varsize = varsize;
            obj.fitfunc = fitfunc;
            obj.margprob = repmat(0.5,1,varsize);
            obj.iters = 0;
        end
        function res = find(obj)
            while((obj.varsize - sum(obj.margprob)) > 0.01)
                obj.iters = obj.iters + 1;
                pop = cga.sample(obj.margprob, 2, obj.varsize);
                [minfit indx] = max(obj.fitfunc.getfit(pop));
                %workarround
                pop = -pop;
                pop(indx, :) = -pop(indx, :);
                obj.margprob = obj.margprob + sum(pop)./ obj.popsize;
            end
        end
    end
    methods (Static)
        function pop = sample(margprob, popsize, varsize)
            pop = ones(popsize, 1)*margprob >= rand(popsize, varsize);
        end
    end
end